$(function() {
    // init date tables
    var jobTable = $("#job_repository_list").dataTable({
        "deferRender": true,
        "processing" : true,
        "serverSide": true,
        "ajax": {
            url: base_url + "/dataCollection/repository/findRepListByPage",
            type:"post",
            data : function ( d ) {
                var obj = {};
                obj.page = d.start;
                obj.limit = d.length;
                return obj;
            }
        },
        "searching": false,
        "ordering": false,
        //"scrollX": true,	// scroll x，close self-adaption
        "columns": [
            {
                "data": 'id',
                "bSortable": false,
                "visible" : false,
                "width":'7%'
            },
            {
                "data": 'repName',
                "visible" : true,
                "width":'25%'
            },
            {
                "data": 'repType',
                "visible" : true,
                "width":'13%'
            },
            {
                "data": 'repBasePath',
                "visible" : true,
                "width":'13%'
            },
            {
                "data": 'dbHost',
                "visible" : true,
                "width":'13%'
            },
            {
                "data": 'dbName',
                "visible" : true,
                "width":'13%'
            },
            {
                "data": I18n.system_opt,
                "width":'15%',
                "render": function ( data, type, row ) {
                    return function(){
                        // data
                        tableData['key'+row.id] = row;

                        // opt
                        var html = '<div class="btn-group">\n' +
                            '     <button type="button" class="btn btn-primary btn-sm">'+ I18n.system_opt +'</button>\n' +
                            '     <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">\n' +
                            '       <span class="caret"></span>\n' +
                            '       <span class="sr-only">Toggle Dropdown</span>\n' +
                            '     </button>\n' +
                            '     <ul class="dropdown-menu" role="menu" _id="'+ row.id +'" >\n' +
                            '       <li><a href="javascript:void(0);" class="opt_edit" >'+ I18n.system_opt_edit +'</a></li>\n' +
                            '       <li><a href="javascript:void(0);" class="opt_del" >'+ I18n.system_opt_del +'</a></li>\n' +
                            '     </ul>\n' +
                            '   </div>';

                        return html;
                    };
                }
            }
        ],
        "language" : {
            "sProcessing" : I18n.dataTable_sProcessing ,
            "sLengthMenu" : I18n.dataTable_sLengthMenu ,
            "sZeroRecords" : I18n.dataTable_sZeroRecords ,
            "sInfo" : I18n.dataTable_sInfo ,
            "sInfoEmpty" : I18n.dataTable_sInfoEmpty ,
            "sInfoFiltered" : I18n.dataTable_sInfoFiltered ,
            "sInfoPostFix" : "",
            "sSearch" : I18n.dataTable_sSearch ,
            "sUrl" : "",
            "sEmptyTable" : I18n.dataTable_sEmptyTable ,
            "sLoadingRecords" : I18n.dataTable_sLoadingRecords ,
            "sInfoThousands" : ",",
            "oPaginate" : {
                "sFirst" : I18n.dataTable_sFirst ,
                "sPrevious" : I18n.dataTable_sPrevious ,
                "sNext" : I18n.dataTable_sNext ,
                "sLast" : I18n.dataTable_sLast
            },
            "oAria" : {
                "sSortAscending" : I18n.dataTable_sSortAscending ,
                "sSortDescending" : I18n.dataTable_sSortDescending
            }
        }
    });

    // table data
    var tableData = {};
    // search btn
    $('#searchBtn').on('click', function(){
        jobTable.fnDraw();
    });

    $('.add').on('click', function(){
        // $("#addModal .form input[name='cronConf']").cronGen({});
        $('#addModal').modal({backdrop: false, keyboard: false}).modal('show');
    });
    var icon = "<i class='fa fa-times-circle'></i> ";
    var addModalValidate = $("#addModal .form").validate({
        errorElement : 'span',
        errorClass : 'help-block',
        focusInvalid : true,
        rules: {
            repName: {
                required: true
            },
            repType: {
                required: true
            },
            createType: {
                required: true
            },
            repUsername: {
                required: true
            },
            repPassword: {
                required: true
            },
            dbType: {
                required: true
            },
            dbAccess: {
                required: true
            },
            dbHost: {
                required: true
            },
            dbPort: {
                required: true
            },
            dbName: {
                required: true
            },
            dbUsername: {
                required: true
            },
            dbPassword: {
                required: true
            }
        },
        messages: {
            repName: {
                required: icon + "请输入资源库名称"
            },
            repType: {
                required: icon + "请选择资源库类型"
            },
            createType: {
                required: icon + "请选择创建方式"
            },
            repUsername: {
                required: icon + "请输入资源库用户名"
            },
            repPassword: {
                required: icon + "请输入资源库密码"
            },
            dbType: {
                required: icon + "请选择数据库类型"
            },
            dbAccess: {
                required: icon + "请选择数据库访问模式"
            },
            dbHost: {
                required: icon + "请输入主机名或IP地址"
            },
            dbPort: {
                required: icon + "请输入数据库端口号"
            },
            dbName: {
                required: icon + "请输入数据库名称"
            },
            dbUsername: {
                required: icon + "请输入数据库登录账号"
            },
            dbPassword: {
                required: icon + "请输入数据库登录密码"
            }
        },
        highlight : function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        success : function(label) {
            label.closest('.form-group').removeClass('has-error');
            label.remove();
        },
        errorPlacement : function(error, element) {
            element.parent('div').append(error);
        },
        submitHandler : function(form) {
            $.post(base_url + "/dataCollection/repository/add",  $("#addModal .form").serialize(), function(data, status) {
                if (data.code == "200") {
                    $('#addModal').modal('hide');
                    layer.open({
                        title: I18n.system_tips ,
                        btn: [ I18n.system_ok ],
                        content: I18n.system_add_suc ,
                        icon: '1',
                        end: function(layero, index){
                            jobTable.fnDraw();
                        }
                    });
                } else {
                    layer.open({
                        title: I18n.system_tips,
                        btn: [ I18n.system_ok ],
                        content: (data.message || I18n.system_add_fail  ),
                        icon: '2'
                    });
                }
            });
        }
    });
    $("#addModal").on('hide.bs.modal', function () {
        $("#addModal .form")[0].reset();
        addModalValidate.resetForm();
        $("#addModal .form .form-group").removeClass("has-error");
    });

    $(".test-conn-add").on('click', function () {
        $.post(base_url + "/dataCollection/repository/testConnection",  $("#addModal .form").serialize(), function(data, status) {
            if (data.code == "200") {
                layer.open({
                    title: I18n.system_tips ,
                    btn: [ I18n.system_ok ],
                    content: '测试通过' ,
                    icon: '1'
                });
            } else {
                layer.open({
                    title: I18n.system_tips,
                    btn: [ I18n.system_ok ],
                    content: (data.message || I18n.system_add_fail  ),
                    icon: '2'
                });
            }
        });
    });

    $(".test-conn-update").on('click', function () {
        $.post(base_url + "/dataCollection/repository/testConnection",  $("#updateModal .form").serialize(), function(data, status) {
            if (data.code == "200") {
                layer.open({
                    title: I18n.system_tips ,
                    btn: [ I18n.system_ok ],
                    content: '测试通过' ,
                    icon: '1'
                });
            } else {
                layer.open({
                    title: I18n.system_tips,
                    btn: [ I18n.system_ok ],
                    content: (data.message || I18n.system_add_fail  ),
                    icon: '2'
                });
            }
        });
    });


    // opt_edit
    $("#job_repository_list").on('click', '.opt_edit',function() {
        var id = $(this).parents('ul').attr("_id");
        var row = tableData['key'+id];
        $("#updateModal .form input[name='id']").val( row.id );
        $("#updateModal .form input[name='repName']").val( row.repName );
        $("#updateModal .form select[name='repType']").val( row.repType );
        $("#updateModal .form input[name='repUsername']").val( row.repUsername );
        $("#updateModal .form input[name='repPassword']").val( row.repPassword );
        $("#updateModal .form select[name='dbType']").val( row.dbType );
        $("#updateModal .form select[name='dbAccess']").val( row.dbAccess );
        $("#updateModal .form input[name='dbHost']").val( row.dbHost );
        $("#updateModal .form input[name='dbPort']").val( row.dbPort );
        $("#updateModal .form input[name='dbName']").val( row.dbName );
        $("#updateModal .form input[name='dbUsername']").val( row.dbUsername );
        $("#updateModal .form input[name='repUsername']").val( row.repUsername );
        $("#updateModal .form input[name='dbPassword']").val( row.dbPassword);


        $('#updateModal').modal({backdrop: false, keyboard: false}).modal('show');
    });
    var updateModalValidate = $("#updateModal .form").validate({
        errorElement : 'span',
        errorClass : 'help-block',
        focusInvalid : true,
        rules: {
            repName: {
                required: true
            },
            repType: {
                required: true
            },
            createType: {
                required: true
            },
            repUsername: {
                required: true
            },
            repPassword: {
                required: true
            },
            dbType: {
                required: true
            },
            dbAccess: {
                required: true
            },
            dbHost: {
                required: true
            },
            dbPort: {
                required: true
            },
            dbName: {
                required: true
            },
            dbUsername: {
                required: true
            },
            dbPassword: {
                required: true
            }
        },
        messages: {
            repName: {
                required: icon + "请输入资源库名称"
            },
            repType: {
                required: icon + "请选择资源库类型"
            },
            createType: {
                required: icon + "请选择创建方式"
            },
            repUsername: {
                required: icon + "请输入资源库用户名"
            },
            repPassword: {
                required: icon + "请输入资源库密码"
            },
            dbType: {
                required: icon + "请选择数据库类型"
            },
            dbAccess: {
                required: icon + "请选择数据库访问模式"
            },
            dbHost: {
                required: icon + "请输入主机名或IP地址"
            },
            dbPort: {
                required: icon + "请输入数据库端口号"
            },
            dbName: {
                required: icon + "请输入数据库名称"
            },
            dbUsername: {
                required: icon + "请输入数据库登录账号"
            },
            dbPassword: {
                required: icon + "请输入数据库登录密码"
            }
        },
        highlight : function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        success : function(label) {
            label.closest('.form-group').removeClass('has-error');
            label.remove();
        },
        errorPlacement : function(error, element) {
            element.parent('div').append(error);
        },
        submitHandler : function(form) {
            $.post(base_url + "/dataCollection/repository/update",  $("#updateModal .form").serialize(), function(data, status) {
                if (data.code == "200") {
                    $('#updateModal').modal('hide');

                    layer.open({
                        title: I18n.system_tips ,
                        btn: [ I18n.system_ok ],
                        content: I18n.system_update_suc ,
                        icon: '1',
                        end: function(layero, index){
                            jobTable.fnDraw();
                        }
                    });
                } else {
                    layer.open({
                        title: I18n.system_tips,
                        btn: [ I18n.system_ok ],
                        content: (data.message || I18n.system_update_fail  ),
                        icon: '2'
                    });
                }
            });
        }
    });
    $("#updateModal").on('hide.bs.modal', function () {
        $("#updateModal .form")[0].reset();
        updateModalValidate.resetForm();
        $("#updateModal .form .form-group").removeClass("has-error");
    });

    // opt_del
    $("#job_repository_list").on('click', '.opt_del',function() {
        var id = $(this).parents('ul').attr("_id");

        layer.confirm( (I18n.system_ok + "删除此资源库吗？") , {
            icon: 3,
            title: I18n.system_tips ,
            btn: [ I18n.system_ok, I18n.system_cancel ]
        }, function(index){
            layer.close(index);

            $.ajax({
                type : 'POST',
                url : base_url + '/dataCollection/repository/delete',
                data : {"id":id},
                dataType : "json",
                success : function(data){
                    if (data.code == 200) {
                        layer.open({
                            title: I18n.system_tips ,
                            btn: [ I18n.system_ok ],
                            content: ("删除资源库" + I18n.system_success),
                            icon: '1',
                            end: function(layero, index){
                                jobTable.fnDraw();
                            }
                        });
                    } else {
                        layer.open({
                            title: I18n.system_tips,
                            btn: [ I18n.system_ok ],
                            content: (data.message || ("删除资源库" + I18n.system_fail)),
                            icon: '2'
                        });
                    }
                },
            });
        });
    });
});